"""发送邮件处理"""
import os
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from config import email


class ProcessingEmail(object):
    def __init__(self):
        self.host = email['host']
        self.port = email['port']
        self.user = email['user']
        self.pwd = email['pwd']
        self.from_addr = email['from_addr']
        self.to_addrs = email['to_addrs']
        all_path = []
        REPORTDIR = os.path.join(os.path.dirname(os.path.abspath(os.path.dirname(__file__))),'report')
        for maindir, subdir, file_list in os.walk(REPORTDIR):
            pass
        for filename in file_list:
            all_path.append(os.path.join(REPORTDIR, filename))
        self.file_name = all_path[0]

    def connect_email_stmp(self):
        """连接stmp服务器"""
        self.stmp = smtplib.SMTP_SSL(host=self.host, port=self.port)
        self.stmp.login(user=self.user, password=self.pwd)

    def made_msg(self):
        """构建邮件"""
        self.msg = MIMEMultipart()
        with open(self.file_name, "rb") as f:
            content = f.read()

        text_msg = MIMEText(content, _subtype="html", _charset="utf-8")  # 创建邮件文本内容
        self.msg.attach(text_msg)  # 将文本内容添加到多组件的邮件中

        report_file = MIMEApplication(content)  # 创建邮件附件
        report_file.add_header("content-disposition", "attachment", filename=self.file_name)
        self.msg.attach(report_file)  # 将附件添加到多组件的邮件中

        self.msg["Subject"] = '自动化测试报告'  # 主题
        self.msg["From"] = self.from_addr  # 发件人
        self.msg["To"] = self.to_addrs  # 收件人（邮件显示的邮件名）

    def send_email(self):
        """发送邮件"""
        self.connect_email_stmp()
        self.made_msg()
        self.stmp.send_message(self.msg, from_addr=self.from_addr, to_addrs=self.to_addrs)


Email = ProcessingEmail()
Email.send_email()
